﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ProgrammingPatterns.DesignPatterns.Creational.Prototype
{
    /// <summary>
    /// Prototype abstract class
    /// </summary>
    /// <typeparam name="T"></typeparam>
    [Serializable]
    public abstract class Prototype<T>
    {
        // Shallow copy
        public T Clone()
        {
            return (T)MemberwiseClone();
        }

        // Deep copy
        public T DeepCopy()
        {
            var stream = new MemoryStream();
            var formatter = new BinaryFormatter();

            formatter.Serialize(stream, this);
            stream.Seek(0, SeekOrigin.Begin);
            
            var copy = (T)formatter.Deserialize(stream);
            stream.Close();
            
            return copy;
        }
    }
}